<template>
  <div class="home">
    <div class="header">
      <div class="logo"></div>
      <div class="titleMain">
        <h1>生产效益</h1>
      </div>
    </div>
    <div class="common-layout linear-gradient">
      <el-container>
        <el-header>
          <div class="top">
            <div class="msg-title">生产效益分析</div>
            <div class="information">
              <div class="left-content">
                <!-- <el-text style="color: #fff">生产效益实时监控与分析</el-text> -->
                <el-carousel autoplay direction="vertical" :interval="3000" indicator-position="none" class="h-full w-full warning-text">
                  <el-carousel-item v-for="(item, index) in warningInfo" :key="index">
                    <span>{{ item }}</span>
                  </el-carousel-item>
                </el-carousel>
              </div>
              <div class="right-content">
                <el-select v-model="teamDateType" placeholder="时间范围" style="width: 100px" @change="dateChange('team', teamDateType)">
                  <el-option v-for="item in dateTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-date-picker
                  v-model="dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期时间"
                  end-placeholder="结束日期时间"
                  class="custom-date-picker"
                  size="small"
                  @change="handleDateRangeChange"
                />
                <span class="label">产线:</span>
                <el-select
                  v-model="searchParams.prodLine"
                  placeholder="全部"
                  clearable
                  size="small"
                  class="custom-select"
                  style="width: 150px"
                  @change="onProdLineChange"
                >
                  <el-option label="全部" value="all" />
                  <el-option label="连退1630" value="cal1630" />
                  <el-option label="连退2150" value="cal2150" />
                  <el-option label="镀锌1870" value="cgl1870" />
                  <el-option label="酸轧2280" value="tcm2280" />
                  <el-option label="重卷1630" value="rcl1630" />
                  <el-option label="重卷2150" value="rcl2150" />
                  <el-option label="重卷1870" value="rcl1870" />
                </el-select>
              </div>
            </div>
          </div>
        </el-header>
        <el-main class="main-container">
          <el-row>
            <!-- 本班效益预估 -->
            <div class="card-container" style="margin-right: 1%">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span class="card-title">本班效益预估</span>
                  </div>
                </template>
                <div class="benefit-estimation">
                  <div class="benefit-item">
                    <div class="benefit-value">{{ estimatedBenefit }}</div>
                    <div class="benefit-label">本班预估效益</div>
                  </div>
                  <div class="benefit-item">
                    <div class="benefit-value">{{ actualBenefit }}</div>
                    <div class="benefit-label">本班已产出效益</div>
                  </div>
                </div>
              </el-card>
            </div>
            <!-- 成本异常分析 -->
            <div class="card-container">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span class="card-title">成本异常分析</span>
                  </div>
                </template>
                <div class="card-body">
                  <div class="table-container">
                    <el-table
                      size="small"
                      :data="exceptionTableData"
                      style="width: 100%"
                      :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
                      :cell-style="{ color: '#fff', textAlign: 'center', height: '3vh' }"
                      @row-click="handleRowClick"
                      :show-overflow-tooltip="true"
                    >
                      <el-table-column prop="extId" label="卷号" width="200" />
                      <el-table-column prop="steelGrade" label="牌号" width="100" />
                      <el-table-column prop="extThick" label="厚度" />
                      <el-table-column prop="extWidth" label="宽度" />
                    </el-table>
                  </div>
                  <div class="graph-container">
                    <div ref="costAnomalyChartRef" style="width: 100%; height: 100%"></div>
                  </div>
                </div>
              </el-card>
            </div>
          </el-row>
          <el-row style="margin-top: 20px">
            <!-- 班组效益对比 -->
            <div class="card-container" style="margin-right: 1%">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span class="card-title">班组效益对比</span>
                  </div>
                </template>
                <div class="card-body">
                  <div class="table-container">
                    <el-table
                      size="small"
                      :data="crewTableData"
                      style="width: 100%"
                      :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
                      :cell-style="{ color: '#fff', textAlign: 'center', height: '3vh' }"
                      :show-overflow-tooltip="true"
                    >
                      <el-table-column prop="turnL2" label="班组" width="70" />
                      <el-table-column prop="prodSec" label="生产用时(h)" width="110" />
                      <el-table-column prop="totalProfit" label="总效益[万元]" width="120" />
                      <el-table-column prop="avgHourProfit" label="小时平均效益[元]" width="150" />
                    </el-table>
                  </div>
                  <div class="graph-container">
                    <div ref="teamComparisonChartRef" style="width: 100%; height: 100%"></div>
                  </div>
                </div>
              </el-card>
            </div>
            <!-- 牌号生产效益 -->
            <div class="card-container">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span class="card-title">牌号生产效益</span>
                  </div>
                </template>
                <div class="card-body">
                  <div class="table-container">
                    <el-table
                      size="small"
                      :data="steelGradeTableData"
                      style="width: 100%"
                      :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
                      :cell-style="{ color: '#fff', textAlign: 'center', height: '3vh' }"
                      :show-overflow-tooltip="true"
                    >
                      <el-table-column prop="steelGrade" label="牌号" />
                      <el-table-column prop="hourlyOutput" label="小时产量" />
                      <el-table-column prop="tonProfit" label="吨钢效益" />
                    </el-table>
                  </div>
                  <div class="graph-container matrix-chart-container" @click="openMatrixChartDialog" style="cursor: pointer">
                    <div ref="brandProductionChartRef" style="width: 100%; height: 100%"></div>
                  </div>
                </div>
              </el-card>
            </div>
          </el-row>
        </el-main>
      </el-container>
    </div>

    <!-- 矩阵图放大对话框 
      title="5#镀锌生产效益矩阵图"-->
    <el-dialog v-model="matrixChartDialogVisible" width="80%" :before-close="closeMatrixChartDialog" class="matrix-chart-dialog">
      <div ref="matrixChartDialogRef" style="width: 100%; height: 600px"></div>
    </el-dialog>

    <el-dialog
      v-model="exceptionVisible"
      :title="exceptionDialogTitle"
      ref="exceptionDialogRef"
      @closed="exceptionVisible = false"
      class="exceptionDialog"
    >
      <el-form :model="exceptionFrom" label-width="auto" class="exceptionForm">
        <el-form-item v-for="item in exceptionItems" :key="item.key" :label="item.label">
          <el-tag :type="exceptionFrom?.[item.key] == '0' ? 'success' : 'danger'">
            {{ exceptionFrom?.[item.key] == '0' ? '正常' : '异常' }}
          </el-tag>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import * as echarts from 'echarts';
  import { processParamApi } from '/@/api/report/index';
  import dayjs from 'dayjs';

  // 下拉框选项
  const dateTypeOptions = ref([
    { value: 'day', label: '日' },
    { value: 'week', label: '周' },
    { value: 'month', label: '月' },
  ]);

  const teamDateType = ref('week');
  const dateRange = ref<[Date, Date] | null>(null);
  const searchParams = reactive({
    prodLine: 'tcm2280',
  });

  // 本班效益预估数据
  const estimatedBenefit = ref('');
  const actualBenefit = ref('');

  // 成本异常分析数据
  const costAnomalyTableData = ref<
    Array<{
      brandNo: string;
      extid: string;
      thick: number;
      width: number;
    }>
  >([]);

  // 班组效益对比数据
  const teamComparisonTableData = ref<
    Array<{
      crew: string;
      profit: number;
      profitHour: number;
      sec: number;
    }>
  >([]);

  // 牌号生产效益数据
  const brandProductionTableData = ref<
    Array<{
      brand: string;
      profitHour: number;
      tonProfit: number;
    }>
  >([]);

  // 图表引用
  const costAnomalyChartRef = ref();
  const teamComparisonChartRef = ref();
  const brandProductionChartRef = ref();
  const matrixChartDialogRef = ref();
  let scatterChartInstance: echarts.ECharts | null = null;
  let teamChartInstance: echarts.ECharts | null = null;
  let exceptionChartInstance: echarts.ECharts | null = null;

  // 对话框控制
  const matrixChartDialogVisible = ref(false);

  // 成本异常分析饼图
  const initCostAnomalyChart = () => {
    // if (exceptionTableData.value.length == 0) {
    //   setTimeout(() => {
    //     initCostAnomalyChart();
    //   }, 500);
    //   return;
    // }
    if (costAnomalyChartRef.value) {
      exceptionChartInstance = echarts.init(costAnomalyChartRef.value);
      updateExceptionChart();
    }
  };

  // 班组效益对比柱状图
  const initTeamComparisonChart = () => {
    // if (crewTableData.value.length == 0) {
    //   setTimeout(() => {
    //     initTeamComparisonChart();
    //   }, 500);
    //   return;
    // }
    if (teamComparisonChartRef.value) {
      teamChartInstance = echarts.init(teamComparisonChartRef.value);
      updateTeamChart();
    }
  };

  // 获取矩阵图配置
  const getMatrixChartOption = () => {
    // 使用动态数据生成矩阵图数据
    const scatterData = brandProductionTableData.value.map((item, index) => ({
      name: item.brand || `牌号${index + 1}`,
      value: [item.profitHour || 0, item.tonProfit || 0],
      percentage: Math.random() * 5 + 0.5, // 随机生成占比，实际项目中应该使用真实数据
    }));

    return {
      title: {
        text: '5#镀锌生产效益矩阵图',
        textStyle: { color: '#fff', fontSize: '16px' },
        left: 'center',
        top: '10%', // 从8%调整到10%，让标题更靠下
      },
      tooltip: {
        trigger: 'item',
        formatter: function (params: any) {
          return `${params.data.name}<br/>小时产量: ${params.data.value[0]}<br/>吨钢效益: ${
            params.data.value[1]
          }<br/>占比: ${params.data.percentage.toFixed(2)}%`;
        },
      },
      xAxis: {
        type: 'value',
        name: '小时产量',
        nameTextStyle: { color: '#fff' },
        axisLabel: { color: '#fff' },
        axisLine: { lineStyle: { color: '#fff' } },
        splitLine: { lineStyle: { color: '#333' } },
        min: 0,
        max: Math.max(...scatterData.map((item) => item.value[0]), 100),
        interval: Math.ceil(Math.max(...scatterData.map((item) => item.value[0]), 100) / 10),
      },
      yAxis: {
        type: 'value',
        name: '吨钢效益',
        nameTextStyle: { color: '#fff' },
        axisLabel: { color: '#fff' },
        axisLine: { lineStyle: { color: '#fff' } },
        splitLine: { lineStyle: { color: '#333' } },
        min: 0,
        max: Math.max(...scatterData.map((item) => item.value[1]), 100),
        interval: Math.ceil(Math.max(...scatterData.map((item) => item.value[1]), 100) / 10),
      },
      series: [
        {
          type: 'scatter',
          data:
            scatterData.length > 0
              ? scatterData
              : [
                  { name: 'H180YD+ZPD', value: [45, 1800], percentage: 1.12 },
                  { name: 'DC50', value: [65, 1200], percentage: 2.34 },
                  { name: 'CR420LA', value: [55, 1600], percentage: 1.89 },
                ],
          symbolSize: function (data: any) {
            return data.percentage * 3;
          },
          itemStyle: {
            color: '#00eaff',
          },
          label: {
            show: true,
            formatter: function (params: any) {
              return params.data.name + '(' + params.data.percentage.toFixed(2) + '%)';
            },
            color: '#fff',
            fontSize: '10px',
            position: 'right',
          },
        },
      ],
      graphic: [
        {
          type: 'line',
          left: '60%',
          top: '10%',
          shape: {
            x1: 0,
            y1: 0,
            x2: 0,
            y2: 100,
          },
          style: {
            stroke: '#ff0000',
            lineWidth: 2,
          },
        },
        {
          type: 'line',
          left: '10%',
          top: '37.5%',
          shape: {
            x1: 0,
            y1: 0,
            x2: 100,
            y2: 0,
          },
          style: {
            stroke: '#ff0000',
            lineWidth: 2,
          },
        },
        {
          type: 'text',
          left: '5%',
          top: '5%',
          style: {
            text: '14.92%',
            fill: '#ff0000',
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        {
          type: 'text',
          left: '5%',
          top: '40%',
          style: {
            text: '50.46%',
            fill: '#ff0000',
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        {
          type: 'text',
          left: '65%',
          top: '5%',
          style: {
            text: '0.92%',
            fill: '#ff0000',
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        {
          type: 'text',
          left: '65%',
          top: '40%',
          style: {
            text: '33.70%',
            fill: '#ff0000',
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
      ],
    };
  };

  const getLabelPosition = (params: any) => {
    console.log('进入函数'); // 此时应能打印
    if (in_out_coefficient_avg.value === undefined || ton_profit_avg.value === undefined) {
      console.error('象限平均值未定义');
      return 'right';
    }
    const x = params.data[0];
    const y = params.data[1];
    // 象限逻辑...
    if (x <= in_out_coefficient_avg.value && y <= ton_profit_avg.value) {
      return 'rightBottom';
    } else if (x >= in_out_coefficient_avg.value && y < ton_profit_avg.value) {
      return 'leftBottom';
    } else if (x < in_out_coefficient_avg.value && y >= ton_profit_avg.value) {
      return 'rightTop';
    } else {
      return 'leftTop';
    }
  };

  interface DeltaPos {
    dx: number;
    dy: number;
  }

  interface GetDeltaPosParams {
    rect: {
      x: number;
      y: number;
    };
    text: string;
  }

  let posMap: Record<string, string> = {};

  const posHandler = {
    // 重置逻辑：操作闭包变量
    reset(): void {
      posMap = {};
    },

    getDeltaPos(params: GetDeltaPosParams): DeltaPos {
      console.log('111111111111111111111'); // 现在应能打印
      const { rect, text } = params;
      const labelWidth = 1500;
      const labelHeight = 600;

      // 👇 2. 直接使用闭包变量 posMap，不再依赖 this
      let gridx = Math.floor(rect.x / labelWidth);
      let gridy = Math.floor(rect.y / labelHeight);
      let currCell: [number, number] = [gridx, gridy];
      let currPos: [number, number] = [gridx * labelWidth, gridy * labelHeight];
      const increaseArr: [number, number][] = [
        [0, -1],
        [1, -1],
        [1, 0],
        [1, 1],
        [0, 1],
        [-1, -1],
        [-1, 0],
        [-1, 1],
      ];
      let found = false;
      const cellKey = `${currCell[0]}-${currCell[1]}`;

      // 👇 3. 操作闭包变量 posMap
      if (posMap[cellKey]) {
        while (!found) {
          for (const [dx, dy] of increaseArr) {
            currCell[0] += dx;
            currCell[1] += dy;
            const newKey = `${currCell[0]}-${currCell[1]}`;
            if (!posMap[newKey]) {
              found = true;
              posMap[newKey] = text;
              currPos = [currCell[0] * labelWidth, currCell[1] * labelHeight];
              break;
            }
          }
          if (found) break;
        }
      } else {
        posMap[cellKey] = text;
      }

      return { dx: currPos[0] - rect.x, dy: currPos[1] - rect.y };
    },
  };

  // 散点图参数
  const quadrantGroup = reactive({
    first: 0,
    second: 0,
    third: 0,
    fourth: 0,
  });
  const start = ref();
  const end = ref();
  const scatterPlotData = ref<any[]>([]);
  const ton_profit_min = ref(0);
  const ton_profit_max = ref(0);
  const in_out_coefficient_min = ref(0);
  const in_out_coefficient_max = ref(0);
  const ton_profit_avg = ref(0);
  const in_out_coefficient_avg = ref(0);
  const scatterPlotOption = ref({
    title: {
      text: `5#镀锌生产效益矩阵图(${start.value} - ${end.value})`,
      left: 'center',
    },
    // grid: {
    //   left: '10%',
    //   right: '12%',
    //   bottom: '20%',
    //   top: '15%',
    // },
    toolbox: {
      feature: {
        saveAsImage: {
          type: 'png', // 下载格式（png/jpeg）
          name: '5#镀锌生产效益矩阵图', // 默认文件名
          backgroundColor: '#fff', // 图片背景色（默认透明）
          pixelRatio: 2, // 高清下载（像素比）
        },
      },
    },
    xAxis: {
      name: '生产系数', //（小时产量 * 合格率）
      type: 'value',
      // nameLocation: 'end',
      // nameGap: -50,
      axisLine: {
        show: false, // 隐藏原始x轴
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: false,
      },
      // 隐藏所有分割线
      splitLine: {
        show: false,
      },
      min: -100,
      max: 100,
    },
    yAxis: {
      name: '钢吨效益（元/吨）',
      type: 'value',
      axisLine: {
        show: false, // 隐藏原始y轴
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: false,
      },
      // 隐藏所有分割线
      splitLine: {
        show: false,
      },
      min: -1400,
      max: 1400,
    },
    tooltip: {
      trigger: 'item',
      formatter: function (params: any) {
        return params.name + '<br/>生产系数：' + params.value[0] + '<br/>钢吨效益：' + params.value[1];
      },
    },
    series: [
      {
        name: '数据点',
        type: 'scatter',
        data: scatterPlotData.value, // 需确保数据格式正确，见下方说明
        // labelLine: {
        //   show: true,
        //   length: 6,
        //   length2: 10,
        //   smooth: 0.1,
        //   lineStyle: { color: '#666', width: 1 },
        // },
        label: {
          show: true,
          position: 'right',
          formatter: '{b}',
          color: '#333',
          distance: 4,
        },
        // 用 labelLayout 回调实现“左右自动靠边”，该回调才支持函数
        labelLayout: (params: any) => {
          return {} as any;
        },
        // 用内部 markLine 渲染十字基准线（随缩放/拖拽联动）
        markLine: {
          silent: true,
          symbol: 'none',
          lineStyle: { color: '#333', width: 1 },
          data: [{ xAxis: in_out_coefficient_avg.value }, { yAxis: ton_profit_avg.value }],
        },
        // labelLayout: function (params: any) {
        //   console.error('labelLayout 回调已进入！');
        //   console.log('labelLayout params 结构：', params);
        //   try {
        //     var dPos = posHandler.getDeltaPos(params);
        //     console.log('getDeltaPos 执行成功，返回偏移：', dPos);
        //     return { dx: dPos.dx, dy: dPos.dy };
        //   } catch (err) {
        //     // 👇 捕获异常，避免函数报错导致日志丢失
        //     console.error('getDeltaPos 执行失败：', err);
        //     return { dx: 0, dy: 0 }; // 出错时返回默认偏移
        //   }
        // },
        itemStyle: {
          color: '#6699FF',
        },
      },
    ],
    graphic: [
      // 象限标签
      {
        type: 'text',
        right: '5%',
        top: '0%',
        style: {
          text: '第一象限',
          fontSize: 14,
          fontWeight: 'bold',
        },
      },
      {
        type: 'text',
        left: '0%',
        top: '0%',
        style: {
          text: '第二象限',
          fontSize: 14,
          fontWeight: 'bold',
        },
      },
      {
        type: 'text',
        left: '0%',
        bottom: '0%',
        style: {
          text: '第三象限',
          fontSize: 14,
          fontWeight: 'bold',
        },
      },
      {
        type: 'text',
        right: '0%',
        bottom: '0%',
        style: {
          text: '第四象限',
          fontSize: 14,
          fontWeight: 'bold',
        },
      },
      // 象限数据标签
      {
        type: 'text',
        left: '0%',
        top: '5%',
        style: {
          text: `${quadrantGroup.second.toFixed(2)}%`,
          fontSize: 12,
          textAlign: 'center',
        },
      },
      {
        type: 'text',
        left: '0%',
        top: '95%',
        style: {
          text: `${quadrantGroup.third.toFixed(2)}%`,
          fontSize: 12,
          textAlign: 'center',
        },
      },
      {
        type: 'text',
        right: '0%',
        top: '5%',
        style: {
          text: `${quadrantGroup.first.toFixed(2)}%`,
          fontSize: 12,
          textAlign: 'center',
        },
      },
      {
        type: 'text',
        right: '0%',
        top: '95%',
        style: {
          text: `${quadrantGroup.fourth.toFixed(2)}%`,
          fontSize: 12,
          textAlign: 'center',
        },
      },
    ],
    // 支持缩放/平移，便于查看密集区域
    dataZoom: [
      { type: 'inside', xAxisIndex: 0, filterMode: 'none' },
      { type: 'inside', yAxisIndex: 0, filterMode: 'none' },
      { type: 'slider', xAxisIndex: 0, height: 10, bottom: 0 },
      { type: 'slider', yAxisIndex: 0, width: 10, right: 0 },
    ],
  });

  // 牌号生产效益矩阵图
  const initBrandProductionChart = () => {
    if (!brandProductionChartRef.value) {
      setTimeout(() => {
        initBrandProductionChart();
      }, 100);
      return;
    }
    if (scatterChartInstance) {
      scatterChartInstance.dispose();
    }
    start.value = dayjs(dateRange.value?.[0]).format('YYYYMMDD HH:mm:ss');
    end.value = dayjs(dateRange.value?.[1]).format('YYYYMMDD HH:mm:ss');
    scatterPlotOption.value.title.text = `5#镀锌生产效益矩阵图(${start.value} - ${end.value})`;
    scatterChartInstance = echarts.init(brandProductionChartRef.value);
    scatterChartInstance.setOption(scatterPlotOption.value);
    // 启用拖拽手势更顺滑
    scatterChartInstance.dispatchAction({ type: 'takeGlobalCursor', key: 'dataZoomSelect', dataZoomSelectActive: true } as any);
  };

  const dateChange = async (cardType: string, val: string) => {
    let dbegin = '';
    let dend = '';

    const today = new Date();

    switch (val) {
      case 'day':
        const dayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate());
        const dayEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);
        dbegin = `${dayStart.getFullYear()}-${String(dayStart.getMonth() + 1).padStart(2, '0')}-${String(dayStart.getDate()).padStart(
          2,
          '0'
        )} 00:00:01`;
        dend = `${dayEnd.getFullYear()}-${String(dayEnd.getMonth() + 1).padStart(2, '0')}-${String(dayEnd.getDate()).padStart(2, '0')} 23:59:59`;
        dateRange.value = [dayStart, dayEnd];
        break;
      case 'week':
        const weekStart = new Date(today.setDate(today.getDate() - 6));
        const weekEnd = new Date(today.setDate(today.getDate() + 6));
        dbegin = `${weekStart.getFullYear()}-${String(weekStart.getMonth() + 1).padStart(2, '0')}-${String(weekStart.getDate()).padStart(
          2,
          '0'
        )} 00:00:01`;
        dend = `${weekEnd.getFullYear()}-${String(weekEnd.getMonth() + 1).padStart(2, '0')}-${String(weekEnd.getDate()).padStart(2, '0')} 23:59:59`;
        dateRange.value = [new Date(dbegin), new Date(dend)];
        break;
      case 'month':
        const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
        const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        dbegin = `${monthStart.getFullYear()}-${String(monthStart.getMonth() + 1).padStart(2, '0')}-${String(monthStart.getDate()).padStart(
          2,
          '0'
        )} 00:00:01`;
        dend = `${monthEnd.getFullYear()}-${String(monthEnd.getMonth() + 1).padStart(2, '0')}-${String(monthEnd.getDate()).padStart(
          2,
          '0'
        )} 23:59:59`;
        dateRange.value = [monthStart, monthEnd];
        break;
    }

    await fetchData(dbegin, dend);
  };

  const handleDateRangeChange = async (val: [Date, Date] | null) => {
    if (val) {
      const [start, end] = val;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      await fetchData(dbegin, dend);
    }
  };

  const onProdLineChange = () => {
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      fetchData(dbegin, dend);
    }
  };

  // 打开矩阵图对话框
  const openMatrixChartDialog = () => {
    matrixChartDialogVisible.value = true;
    nextTick(() => {
      initMatrixChartDialog();
    });
  };

  // 关闭矩阵图对话框
  const closeMatrixChartDialog = () => {
    matrixChartDialogVisible.value = false;
  };

  // 初始化对话框中的矩阵图
  const initMatrixChartDialog = () => {
    if (matrixChartDialogRef.value) {
      start.value = dayjs(dateRange.value?.[0]).format('YYYYMMDD HH:mm:ss');
      end.value = dayjs(dateRange.value?.[1]).format('YYYYMMDD HH:mm:ss');
      scatterPlotOption.value.title.text = `5#镀锌生产效益矩阵图(${start.value} - ${end.value})`;
      scatterChartInstance = echarts.init(matrixChartDialogRef.value);
      const option = scatterPlotOption.value;
      scatterChartInstance.setOption(option);
    }
  };
  //------------------------------------------------------------------------  异常窗口 ------------------------------------------------
  const exceptionVisible = ref(false);
  const exceptionDialogTitle = ref('成本异常分析');
  const exceptionFrom = ref<any>({});
  const exceptionItems = ref([
    { key: 'pressAirExc', label: '压缩空气异常' },
    { key: 'steamExc', label: '蒸汽异常' },
    { key: 'saltExc', label: '脱盐水异常' },
    { key: 'gasExc', label: '煤气异常' },
    { key: 'fineNitrogenExc', label: '精氮异常' },
    { key: 'roughNitrogenExc', label: '粗氮异常' },
    { key: 'cleanWaterExc', label: '清洗段水异常' },
    { key: 'hydrogenExc', label: '氢气异常' },
    { key: 'powerMountExc', label: '电量异常' },
    { key: 'noilamountExc', label: '涂油量异常' },
    { key: 'zincExc', label: '锌层异常' },
  ]);

  const handleRowClick = (row: any) => {
    exceptionFrom.value = { ...row };
    exceptionVisible.value = true;
    exceptionDialogTitle.value = `卷号${row.extId}异常详细`;
  };

  //------------------------------------------------------------------------  接口調用 ------------------------------------------------

  const warningInfo = ref([]);
  let interval: any = null;

  // 本班效益预估
  const getTechCrewProfit = async () => {
    try {
      const res = await processParamApi.techCrewProfit();
      estimatedBenefit.value = `${res.data.data.estimate.toFixed(2)}万元`;
      actualBenefit.value = `${res.data.data.acti.toFixed(2)}万元`;
      toWarningInfo(res.data.data.exec);
    } catch (e: any) {
      console.error('获取当前班组预估收益失败：' + e);
    }
  };

  interface CrewTableData {
    turnL2: string;
    prodSec: string;
    totalProfit: string;
    avgHourProfit: string;
  }

  const tableData = ref<any>([]);
  const crewTableData = ref<CrewTableData[]>([]);
  const exceptionTableData = ref<any>([]);
  const steelGradeTableData = ref<any>([]);

  const fetchData = async (start: string, end: string) => {
    try {
      const param = {
        startTime: start,
        endTime: end,
        line: searchParams.prodLine,
      };
      const res = await processParamApi.fetchData(param);
      tableData.value = res.data;
      toCrewData(res.data);
      toSteelGradeData(res.data);
      exceptionTableData.value = tableData.value
        .filter(
          (item: any) =>
            item.pressAirExc == '1' ||
            item.steamExc == '1' ||
            item.saltExc == '1' ||
            item.gasExc == '1' ||
            item.fineNitrogenExc == '1' ||
            item.roughNitrogenExc == '1' ||
            item.cleanWaterExc == '1' ||
            item.hydrogenExc == '1' ||
            item.powerMountExc == '1' ||
            item.noilamountExc == '1' ||
            item.zincExc == '1'
        )
        .map((item: any) => {
          return {
            ...item,
            extThick: item.extThick / 1000,
            extWidth: item.extWidth / 10,
          };
        });
      updateExceptionChart();
      ElMessage.success('获取数据成功');
    } catch (error) {
      console.error('获取数据失败:', error);
      ElMessage.error('获取数据失败');
    }
  };

  onMounted(() => {
    // 默认加载本周数据
    const today = new Date();
    const weekStart = new Date(today.setDate(today.getDate() - 6));
    const weekEnd = new Date(today.setDate(today.getDate() + 6));
    // dateRange.value = [weekStart, weekEnd];

    const dbegin = `${weekStart.getFullYear()}-${String(weekStart.getMonth() + 1).padStart(2, '0')}-${String(weekStart.getDate()).padStart(
      2,
      '0'
    )} 00:00:00`;
    const dend = `${weekEnd.getFullYear()}-${String(weekEnd.getMonth() + 1).padStart(2, '0')}-${String(weekEnd.getDate()).padStart(2, '0')} 23:59:59`;
    dateRange.value = [new Date(dbegin), new Date(dend)];

    // 调用接口获取数据
    // fetchData(dbegin, dend);

    // 初始化數據
    fetchData(dbegin, dend);
    getTechCrewProfit();
    interval = setInterval(() => {
      getTechCrewProfit();
    }, 600000);

    // 初始化图表
    nextTick(() => {
      initCostAnomalyChart();
      initTeamComparisonChart();
      initBrandProductionChart();

      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        const charts = [
          echarts.getInstanceByDom(costAnomalyChartRef.value),
          echarts.getInstanceByDom(teamComparisonChartRef.value),
          echarts.getInstanceByDom(brandProductionChartRef.value),
        ];
        charts.forEach((chart) => {
          if (chart) chart.resize();
        });
      });
    });
  });

  onUnmounted(() => {
    clearInterval(interval);
  });

  // ---------------------------------------   函数   -------------------------------------------
  const toCrewData = (data: any) => {
    const groupedData = data.reduce((map: any, item: any) => {
      const turnL2 = item.turnL2;
      const prodHours = item.prodSec / 3600;
      const itemProfit = Number(item.tonProfitTotal);
      if (map.has(turnL2)) {
        const existing = map.get(turnL2);
        existing.prodSec += prodHours;
        existing.totalProfit += Number(itemProfit);
      } else {
        map.set(turnL2, {
          turnL2,
          prodSec: prodHours,
          totalProfit: itemProfit,
        });
      }
      return map;
    }, new Map());

    // 转换为数组并计算平均值
    crewTableData.value = Array.from(groupedData.values())
      .map((item: any) => ({
        turnL2: item.turnL2,
        prodSec: item.prodSec.toFixed(2),
        totalProfit: item.totalProfit.toFixed(2),
        avgHourProfit: ((item.totalProfit * 10000) / item.prodSec).toFixed(2),
      }))
      .sort((a, b) => a.turnL2.localeCompare(b.turnL2));
    updateTeamChart();
  };

  interface OriginalItem {
    steelGrade: string;
    extWeight: number;
    tonProfit: number;
    prodSec: number;
    tonProfitTotal: number;
    defectLevel: string;
    surfacecode: string;
  }

  interface GroupedItem {
    steelGrade: string;
    extWeight: number;
    totalTonProfit: number;
    prodSec: number;
    conWeight: number;
  }

  interface ResultItem {
    steelGrade: string;
    hourlyOutput: number;
    tonProfit: number;
    extWeight: number;
    conRate: number;
    in_out_coefficient: number;
  }

  // 常量定义
  const SECOND_TO_HOUR = 3600;
  const KILOGRAM_TO_TON = 1000;

  const toSteelGradeData = (data: OriginalItem[]) => {
    // 分组并计算同时进行，减少一次循环
    const groupedMap = data.reduce((acc, curr) => {
      const key = curr.steelGrade;
      const totalTonProfit = curr.tonProfitTotal * 10000;

      if (!acc.has(key)) {
        acc.set(key, {
          steelGrade: key,
          extWeight: 0,
          totalTonProfit: 0,
          prodSec: 0,
          conWeight: 0,
        });
      }

      const group = acc.get(key)!;
      group.extWeight += Number(curr.extWeight);
      group.totalTonProfit += totalTonProfit;
      group.prodSec += Number(curr.prodSec);
      group.conWeight += curr.defectLevel != curr.surfacecode ? 0 : Number(curr.extWeight);

      return acc;
    }, new Map<string, GroupedItem>());

    // 计算最终结果并处理可能的除以零情况
    steelGradeTableData.value = Array.from(groupedMap.values()).map((item): ResultItem => {
      const tons = item.extWeight / KILOGRAM_TO_TON;
      const hours = item.prodSec / SECOND_TO_HOUR;
      const conRate = item.extWeight > 0 ? item.conWeight / item.extWeight : 0.0;

      // 处理除以零的情况
      const hourlyOutput = hours > 0 ? (tons / hours).toFixed(2) : '0.00';
      const tonProfit = tons > 0 ? (item.totalTonProfit / tons).toFixed(2) : '0.00';
      const in_out_coefficient = (Number(hourlyOutput) * conRate).toFixed(2);

      return {
        steelGrade: item.steelGrade,
        extWeight: item.extWeight,
        hourlyOutput: Number(hourlyOutput),
        tonProfit: Number(tonProfit),
        conRate,
        in_out_coefficient: Number(in_out_coefficient),
      };
    });
    const totalWeight = steelGradeTableData.value.reduce((sum: number, item: any) => sum + item.extWeight, 0);
    scatterPlotData.value = steelGradeTableData.value.map((item: any) => ({
      value: [item.in_out_coefficient, item.tonProfit],
      name: `${item.steelGrade}(${((item.extWeight / totalWeight) * 100).toFixed(2)}%)`,
    }));
    updateChart();
  };

  const toWarningInfo = (data: any) => {
    warningInfo.value = data.map((value: any) => {
      const exceptions = exceptionItems.value
        .map((item: any) => (value[item.key] == '1' ? `${item.label}，` : ''))
        .filter((reason: string) => reason.length > 0)
        .join('')
        .slice(0, -1);
      return `卷号：${value.extid}，牌号：${value.steelgrade}，厚度：${value.extThick / 1000}，宽度：${value.extWidth / 10}，异常原因：${exceptions}`;
    });
  };

  const updateChart = () => {
    scatterPlotOption.value.series[0].data = scatterPlotData.value;
    ton_profit_avg.value = steelGradeTableData.value.reduce((sum: number, item: any) => sum + item.tonProfit, 0) / steelGradeTableData.value.length;
    in_out_coefficient_avg.value =
      steelGradeTableData.value.reduce((sum: number, item: any) => sum + item.in_out_coefficient, 0) / steelGradeTableData.value.length;
    ton_profit_min.value = steelGradeTableData.value.reduce((min: number, item: any) => Math.min(min, item.tonProfit), Number.MAX_SAFE_INTEGER);
    in_out_coefficient_min.value = steelGradeTableData.value.reduce(
      (min: number, item: any) => Math.min(min, item.in_out_coefficient),
      Number.MAX_SAFE_INTEGER
    );
    ton_profit_max.value = steelGradeTableData.value.reduce((max: number, item: any) => Math.max(max, item.tonProfit), Number.MIN_SAFE_INTEGER);
    in_out_coefficient_max.value = steelGradeTableData.value.reduce(
      (max: number, item: any) => Math.max(max, item.in_out_coefficient),
      Number.MIN_SAFE_INTEGER
    );

    scatterPlotOption.value.xAxis.min = in_out_coefficient_min.value;
    scatterPlotOption.value.yAxis.min = ton_profit_min.value;
    scatterPlotOption.value.xAxis.max = in_out_coefficient_max.value;
    scatterPlotOption.value.yAxis.max = ton_profit_max.value;

    // 计算象限比重
    const totalWeight = steelGradeTableData.value.reduce((sum: number, item: any) => sum + item.extWeight, 0);
    // 初始化象限组
    const quadrantGroup = { first: 0, second: 0, third: 0, fourth: 0 };
    steelGradeTableData.value.forEach((item: any) => {
      if (item.in_out_coefficient >= in_out_coefficient_avg.value && item.tonProfit >= ton_profit_avg.value) {
        quadrantGroup.first += Number((item.extWeight / totalWeight) * 100);
      }
      if (item.in_out_coefficient > in_out_coefficient_avg.value && item.tonProfit < ton_profit_avg.value) {
        quadrantGroup.fourth += Number((item.extWeight / totalWeight) * 100);
      }
      if (item.in_out_coefficient < in_out_coefficient_avg.value && item.tonProfit > ton_profit_avg.value) {
        quadrantGroup.second += Number((item.extWeight / totalWeight) * 100);
      }
      if (item.in_out_coefficient <= in_out_coefficient_avg.value && item.tonProfit <= ton_profit_avg.value) {
        quadrantGroup.third += Number((item.extWeight / totalWeight) * 100);
      }
    });
    scatterPlotOption.value.graphic[4].style.text = `${quadrantGroup.second.toFixed(2)}%`;
    scatterPlotOption.value.graphic[5].style.text = `${quadrantGroup.third.toFixed(2)}%`;
    scatterPlotOption.value.graphic[6].style.text = `${quadrantGroup.first.toFixed(2)}%`;
    scatterPlotOption.value.graphic[7].style.text = `${quadrantGroup.fourth.toFixed(2)}%`;

    scatterPlotOption.value.series[0].markLine = {
      silent: true,
      symbol: 'none',
      lineStyle: { color: '#333', width: 1 },
      data: [{ xAxis: in_out_coefficient_avg.value }, { yAxis: ton_profit_avg.value }],
    };

    scatterPlotOption.value.series[0].labelLayout = (params: any) => {
      const pointData = scatterPlotData.value[params.dataIndex];
      // 提取第一个值（64.32 对应的数值）
      const firstValue = pointData.value[0];
      const isRight = firstValue >= in_out_coefficient_avg.value;
      // 仅演示一次打印，确认回调生效

      return {
        // 通过水平位移和对齐方向实现左右效果
        dx: isRight ? 0 : -15,
        align: isRight ? 'left' : 'right',
        // 同时告知引导线端点相对移动（可选）
        // labelLinePoints: params.labelLinePoints // 若需要自定义可基于 params 计算
        hideOverlap: true,
        moveOverlap: 'shiftY',
      } as any;
    };
    posHandler.reset();
    if (scatterChartInstance) {
      start.value = dayjs(dateRange.value?.[0]).format('YYYYMMDD HH:mm:ss');
      end.value = dayjs(dateRange.value?.[1]).format('YYYYMMDD HH:mm:ss');
      scatterPlotOption.value.title.text = `5#镀锌生产效益矩阵图(${start.value} - ${end.value})`;
      scatterChartInstance.setOption(scatterPlotOption.value, true);
    } else {
      initBrandProductionChart(); // 若实例丢失，重新初始化
    }
  };

  const updateTeamChart = () => {
    // 使用动态数据
    const xAxisData = crewTableData.value.map((item) => item.turnL2 || '班组');
    const profitData = crewTableData.value.map((item) => item.totalProfit || 0);
    const profitHourData = crewTableData.value.map((item) => item.avgHourProfit || 0);

    const option = {
      title: {
        text: '班组效益对比',
        textStyle: { color: '#fff', fontSize: '12px' },
        left: 'center',
        top: '5%',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
      },
      grid: {
        left: '15%',
        right: '15%',
        bottom: '20%',
        top: '15%',
      },
      legend: {
        data: ['总效益（万元）', '小时平均效益（元）'],
        textStyle: { color: '#fff', fontSize: '10px' },
        bottom: '5%',
      },
      xAxis: {
        type: 'category',
        data: xAxisData.length > 0 ? xAxisData : ['A', 'B', 'C', 'D'],
        axisLabel: { color: '#fff' },
        axisLine: { lineStyle: { color: '#fff' } },
      },
      yAxis: [
        {
          type: 'value',
          name: '总效益（万元）',
          position: 'left',
          axisLabel: { color: '#fff' },
          axisLine: { lineStyle: { color: '#fff' } },
          splitLine: { lineStyle: { color: '#333' } },
        },
        {
          type: 'value',
          name: '小时平均效益（元）',
          position: 'right',
          axisLabel: { color: '#fff' },
          axisLine: { lineStyle: { color: '#fff' } },
          splitLine: { lineStyle: { color: '#333' } },
        },
      ],
      series: [
        {
          name: '总效益（万元）',
          type: 'bar',
          data: profitData.length > 0 ? profitData : [],
          itemStyle: { color: '#0072ff' },
          yAxisIndex: 0,
        },
        {
          name: '小时平均效益（元）',
          type: 'bar',
          data: profitHourData.length > 0 ? profitHourData : [],
          itemStyle: { color: '#ff6b35' },
          yAxisIndex: 1,
        },
      ],
    };
    teamChartInstance?.setOption(option);
  };

  const updateExceptionChart = () => {
    // 生成饼图数据
    const pieData = exceptionItems.value
      .map((item: any) => {
        const key = item.key;
        const label = item.label;
        const count = exceptionTableData.value.filter((row: any) => row[key] == '1').length;
        return count > 0 ? { name: label, value: count } : null;
      })
      .filter((item: any) => item !== null);

    const totalAnomalies = pieData.reduce((sum: any, item: any) => sum + item.value, 0);

    const option = {
      title: {
        text: '各种成本异常原因占比',
        textStyle: { color: '#fff', fontSize: '12px' },
        left: 'center',
        top: '5%',
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      series: [
        {
          name: '异常原因',
          type: 'pie',
          radius: '55%',
          center: ['50%', '60%'],
          data: pieData.map((item: any) => ({
            name: item.name,
            value: item.value,
            percent: ((item.value / totalAnomalies) * 100).toFixed(2),
          })),
          label: {
            formatter: '{b}',
            color: '#fff',
          },
          labelLine: {
            lineStyle: {
              color: '#fff',
            },
          },
        },
      ],
    };
    exceptionChartInstance?.setOption(option, true);
  };
</script>

<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 2px 4px rgba(51, 102, 153, 0.5);

  .home {
    height: 105vh;
    overflow: hidden !important;
  }

  .top {
    width: 98%;
    height: 18vh;
    margin: 0.5% auto;
    color: #fff;
    font-size: 1.2rem;
    display: flex;
    flex-direction: column;

    .msg-title {
      margin-top: -7vh;
      margin-left: 0;
      background-image: -webkit-linear-gradient(left, #0072ff, #00eaff, #01aaff);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      font-size: 2vh;
      font-weight: bolder;
      text-align: left;
      margin-bottom: 2vh;
    }

    .information {
      margin-left: 0;
      margin-top: 0;
      color: #fff;
      width: 98%;
      height: 8vh;
      border: 2px solid #3981d9;
      border-radius: 5px;
      padding: 0 0.2vw;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left-content {
        flex: 1;
        text-align: left;
        padding-left: 1vw;
        color: #fff;
        position: relative;

        .warning-text {
          width: 100%;
          height: 4vh;
          position: absolute;
          top: -1vh;
          font-size: 12px;
        }
      }

      .right-content {
        flex: 0 0 auto;
        padding-right: 1vw;
      }
    }
  }

  .main-container {
    width: 98%;
    height: 80%;
    flex-wrap: wrap;
    overflow: hidden;
    margin-top: -0.5vh;
  }

  .main-container .card-container {
    width: 49.5%;
    border-radius: @border-radius;
    height: 38vh;
    background-color: transparent !important;
    box-shadow: @box-shadow;
    transition: box-shadow 0.3s ease;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 2vw;
    position: relative;
    z-index: 1;
    flex-direction: row;

    .card-header {
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .card-title {
        background-image: -webkit-linear-gradient(left, #0072ff, #00eaff, #01aaff);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-size: 2vh;
        font-weight: bolder;
      }
    }

    :deep(.el-card) {
      width: 100%;
      height: 100%;
      background-color: transparent !important;
      border-radius: @border-radius;
      border: #0072ff solid 2px;
    }

    .card-body {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
      max-height: 25vh;
      max-width: 45vw;

      .graph-container {
        height: 30vh;
        width: 35vw;
        display: flex;
        justify-content: center;
        color: #fff;

        // 为牌号生产效益的矩阵图添加特殊样式
        &.matrix-chart-container {
          height: 24vh; // 再增加高度
          margin-top: 2vh; // 再向下移动
        }
      }

      .table-container {
        width: 40vw;
        display: flex;
        justify-content: center;

        :deep(.el-table) {
          height: 240px;
          overflow: hidden;
          overflow-y: auto;
          width: 100%;
          z-index: 1;
          --el-table-row-hover-bg-color: unset;
          --el-table-border-color: transparent;
        }
      }
    }
  }

  .card-container:hover {
    box-shadow: 0 8px 16px rgba(51, 102, 153, 1);
  }

  // 本班效益预估样式
  .benefit-estimation {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 100%;
    padding: 20px;

    .benefit-item {
      text-align: center;
      flex: 1;

      .benefit-value {
        color: #00cfff;
        font-size: 32px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .benefit-label {
        color: #8ecfff;
        font-size: 16px;
      }
    }
  }

  /* 表格样式 */
  :deep(.el-table) {
    background-color: transparent;
    --el-table-border: none;
    color: white;

    :deep(.el-table__row:nth-child(odd)) {
      background-color: #223671;
    }

    .el-table__row {
      height: auto !important;
      line-height: 1.2;
    }

    .el-table__cell {
      padding: 2px 4px !important;

      .cell {
        font-size: 16px !important;
        transform: scale(0.85);
        transform-origin: left;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }

  :deep(.el-table__inner-wrapper::before) {
    left: 0;
    bottom: 0;
    width: 100%;
    height: 0;
  }

  :deep(.el-table th),
  :deep(.el-table tr),
  :deep(.el-table td) {
    background-color: transparent;
  }

  // 表单控件样式
  :deep(.el-select) {
    width: 1rem;
    right: 1rem;
    background-color: transparent !important;
    color: #fff;
  }

  :deep(.el-select__wrapper) {
    background-color: transparent !important;
  }

  :deep(.el-input__wrapper) {
    background-color: #223671 !important;
    box-shadow: none !important;
  }

  :deep(.el-input__inner) {
    color: #fff !important;
  }

  :deep(.el-select-dropdown__item) {
    color: #fff !important;
  }

  :deep(.el-select-dropdown__item.hover, .el-select-dropdown__item:hover) {
    background-color: #2f59af !important;
  }

  :deep(.el-select-dropdown) {
    background-color: #223671 !important;
    border: 1px solid #2f59af !important;
  }

  :deep(.custom-date-picker.el-date-editor) {
    width: 260px !important;
    height: 28px;
    background-color: transparent !important;
    border: 1px solid #fff;
    box-shadow: none;
  }

  :deep(.el-date-picker) {
    background-color: #223671 !important;
    border: 1px solid #2f59af !important;
    color: #fff !important;
  }

  :deep(.el-date-picker__header) {
    color: #fff !important;
  }

  :deep(.el-date-picker__header-label) {
    color: #fff !important;
  }

  :deep(.el-date-table th) {
    color: #fff !important;
  }

  :deep(.el-date-table td) {
    color: #fff !important;
  }

  :deep(.el-date-table td.available:hover) {
    color: #fff !important;
    background-color: #2f59af !important;
  }

  :deep(.el-date-table td.current:not(.disabled) span) {
    background-color: #2f59af !important;
    color: #fff !important;
  }

  :deep(.el-date-picker__time-header) {
    color: #fff !important;
  }

  :deep(.el-time-panel) {
    background-color: #223671 !important;
    border: 1px solid #2f59af !important;
  }

  :deep(.el-time-panel__content) {
    color: #fff !important;
  }

  :deep(.el-time-spinner__item) {
    color: #fff !important;
  }

  :deep(.el-time-spinner__item.active:not(.disabled)) {
    color: #fff !important;
    background-color: #2f59af !important;
  }

  :deep(.el-time-spinner__item:hover:not(.disabled):not(.active)) {
    background-color: #2f59af !important;
  }

  :deep(.el-date-editor .el-range-separator) {
    color: #fff !important;
  }

  :deep(.el-date-editor .el-range-input) {
    color: #fff !important;
  }

  :deep(.el-date-editor .el-range__icon) {
    color: #fff !important;
  }

  :deep(.el-date-editor .el-range__close-icon) {
    color: #fff !important;
  }

  .right-content .label {
    margin-right: 18px;
    margin-left: 5px;
    white-space: nowrap;
    font-size: 12px;
    min-width: 80px;
    text-align: right;
  }

  // 矩阵图对话框样式
  :deep(.matrix-chart-dialog) {
    .el-dialog {
      // background-color: #1a1a2e;
      border: 2px solid #0072ff;
    }

    // .el-dialog__header {
    //   // background-color: #16213e;
    //   border-bottom: 1px solid #0072ff;
    // }

    // .el-dialog__title {
    //   color: #fff;
    // }

    // .el-dialog__body {
    //   // background-color: #1a1a2e;
    //   color: #fff;
    // }
  }

  .custom-input,
  .custom-select,
  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper) {
    height: 28px;
    line-height: 28px;
    background-color: #0a1a3a !important;
    border: 1px solid #3a5a8a !important;
    border-radius: 3px !important;
    color: #c0c4cc !important;
    box-shadow: none !important;
    font-size: 12px !important;
  }

  @baseFontSize: 16px;
  .exceptionForm {
    display: grid;
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 15px;
    background-color: #f9fafc;
    border-radius: 8px;

    .el-form-item {
      margin: 0;
      padding: 10px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      }

      .el-form-item__label {
        padding-right: 12px;
        font-weight: 500;
        color: #4e5969;
        min-width: 90px;
      }
    }

    // 响应式调整，屏幕宽度较宽时调整列数
    @media (min-width: 1024px) {
      grid-template-columns: repeat(3, 1fr);
    }

    @media (min-width: 768px) {
      grid-template-columns: repeat(2, 1fr);
    }
  }
</style>
